$(document).ready(function() {

function fnFormatDetailsAndOpenInCallback(nTr) {
	var aData = oTable.fnGetData(nTr);
	var sTable =	'<table id="costintervalTable" cellpadding="0" cellspacing="0" border="0" style="padding-left:50px; width:35%;" class="table table-striped table-bordered"></table>';
	
	
	oDetailTable = $(sTable).dataTable({
		 "bProcessing": true,
	     "bServerSide": false,
	     "sAjaxSource" : 'costIntervals',
	     "fnServerParams": function ( aoData ) {
	    	 if(aData == null){
	    		 aoData.push( { "name": "ID", "value": currentOpenedRowData.ID } );
	    		 return;
	    	 }
	    	 aoData.push( { "name": "ID", "value": aData.ID } );
	     },
		"aoColumns" : [{
			"sTitle" : "ID",
			"mData" : "ID"
		}, {
			"sTitle" : "Start Date",
			"mData" : "COST_START"
		}, {
			"sTitle" : "End Date",
			"mData" : "COST_END"
		}, {
			"sTitle" : "Fix Costs",
			"mData" : "FIX_COSTS"
		}, {
			"sTitle" : "Total Costs",
			"mData" : "TOTAL_COSTS"
		}, {
			"sTitle" : "Cost per Day",
			"mData" : "DAILY_COST",
			"sWidth" : "150px"
		}, {
			"sTitle" : "Aktion",
            "mData": null,
            "sClass": "center",
            "sDefaultContent": '<a href="" class="editor_remove">Delete</a>',
//            <a href="" class="editor_edit">Edit</a> / 
            "sWidth" : "200px"
        }
		]
		,"bAutoWidth" : true
	});
}


$('#example tbody tr').die().live('click', function(e) {
	if($(e.target).prop("tagName") != "TD") return; // clicking on campaigncost edit link
	var nTr = $(this)[0]; // .parents('tr')[0];
	
	if (oTable.fnIsOpen(nTr)) {
		oTable.fnClose(nTr);
	} else {
		if(currentOpenenedRow != undefined){
			oTable.fnClose(currentOpenenedRow);
		}
		currentOpenenedRow = nTr;
		currentOpenedRowData = oTable.fnGetData(nTr) || currentOpenedRowData;
		fnFormatDetailsAndOpenInCallback(nTr);
		var sLink = $('<a href="" class="editor_create">Create new Costinterval</a>');
		var detailsDOM = sLink.after(oDetailTable);
		oTable.fnOpen(nTr,detailsDOM , 'details');
		
		 costintervalEditor = new $.fn.dataTable.Editor( {
	        "ajaxUrl": "costIntervals",
	        "idSrc": "ID",
	        "domTable": "#costintervalTable",
	        "ajax": function ( method, ajaxUrl, aoData, fnCallback, errorCallback ) {
		    	 aoData.data.CAMPAIGN_ID = currentOpenedRowData.ID;//aData.ID;
		    	 if (aoData.action === 'create') {
		            $.ajax( {
		                dataType: 'json',
		                contentType: "application/json;charset=UTF-8",
		                type: 'POST',
		                url: ajaxUrl,
		                data: JSON.stringify(aoData.data),
		                success: function(){
//		                	oTable.fnOpen(nTr, "<div>details</div>", 'details');
		                	window.location.reload();
//		                	fnCallback();
		                },
		                error : function (xhr, error, thrown) {
							var results = $.parseJSON(xhr.responseText);
							if(results.errors != undefined){
								$.each(results.errors, function(index){
									costintervalEditor.error(results.errors[index].key, results.errors[index].value);
								});	
							}else{
								alert("Error on Server");	
							}
				          errorCallback( xhr, error, thrown );
						}
		            } );
		    	 }else if(aoData.action === 'remove') {
						$.ajax({
							type : 'DELETE',
							url : ajaxUrl + "/" + aoData.data[0] + '?campaignId=' 
									+ oTable.fnGetData(currentOpenenedRow).ID ,
							// data : {"test" :
							// 123},//JSON.stringify(aoData.data),
							success : function() {
								window.location.reload();
								fnCallback();
							},
							error : function(e) {
								alert("Error on Server");
							}
						});
					} else if (aoData.action === 'edit') {
						aoData.data.ID = aoData.id;
						
						$.ajax({
							dataType : 'json',
							contentType : "application/json;charset=UTF-8",
							type : 'PUT',
							url : ajaxUrl,
							data : JSON.stringify(aoData.data),
							success : function() {
								window.location.reload();
								fnCallback();
							},
							error : function (xhr, error, thrown) {
								var results = $.parseJSON(xhr.responseText);
								if(results.errors != undefined){
									$.each(results.errors, function(index){
										editor.error(results.errors[index].key, results.errors[index].value);
									});	
								}else{
									alert("Error on Server");	
								}
					          errorCallback( xhr, error, thrown );
							}
						});
					}else{
						alert("Noch nicht implementiert");
					}
		        },
	        "fields": [ {
	                "label": "Start Date:",
	                "name": "COST_START",
	                	"type" : "date",
						"dateFormat" : 'yy-mm-dd'
	            }, {
	                "label": "End Date:",
	                "name": "COST_END",
	                "type" : "date",
					"dateFormat" : 'yy-mm-dd'
	            }, {
	                "label": "Fix Costs:",
	                "name": "FIX_COSTS"
	            }, {
	                "label": "Number of Variable:",
	                "name": "NUMBER_OF_VARIABLE"
	            }
	        ]
	    } );
	    
	
	  //New record
	    $('a.editor_create').on('click', function (e) {
	        e.preventDefault();
	        
	        if(oTable.fnGetData(currentOpenenedRow).COST_PER_VARIABLE === 0.0){
	    		costintervalEditor.disable('NUMBER_OF_VARIABLE');
	    	}

	        costintervalEditor.create(
	            'Create new Costinterval',
	            { "label": "Add", "fn": function () { costintervalEditor.submit() } }
	        );
	    } );

	    // Edit record
	    $('#costintervalTable').on('click', 'a.editor_edit', function (e) {
	        e.preventDefault();

	        costintervalEditor.edit(
	            $(this).parents('tr')[0],
	            'Edit record',
	            { "label": "Update", "fn": function () { costintervalEditor.submit() } }
	        );
	    } );

	    // Delete a record (without asking a user for confirmation)
	    $('#costintervalTable').on('click', 'a.editor_remove', function (e) {
	        e.preventDefault();

	        costintervalEditor.remove( $(this).parents('tr')[0], '123', false, false );
	        costintervalEditor.submit();
	    } );
	  
	}
}).children().click(function(e) {
  return false;
});

});